package com.kehutong.payment.util;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 根据时间戳生成ID号工具，长度为18位=yyMMddHHmmssSSS+XXX
 */
public class IdGeneratorUtil {
    static volatile int index = 100;

    /**
     * 根据服务器当前时间生成ID
     */
    public static String generate() {
        StringBuilder buf = new StringBuilder();
        buf.append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMddHHmmssSSS")));
        if (index >= 1000) {
            index = 100;
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                generate();
            }
        }
        buf.append(index ++);
        return buf.toString();
    }

    /**
     * 根据服务器当前时间生成ID
     */
    public static long generateLong() {
        return Long.parseLong(generate());
    }

}
